package tool;

import c.c.d.s.s.o.ts.as.TokenCustomizeAuthorizationServer;
import lombok.SneakyThrows;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.security.Key;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Base64;

/**
 * {@link KeyStore} 相关工具
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-07-17 15:15
 */
@SpringBootTest(classes = TokenCustomizeAuthorizationServer.class)
@RunWith(SpringRunner.class)
public class KeyStoreTools {

    private static final String KEYSTORE_NAME = "authorization-server.jks";

    private static final String KEYSTORE_PASS = "SCLiKe11040218";

    private static final String AUTHORIZATION_SERVER_JWT_KEYPAIR_ALIAS = "authorization-server-jwt-keypair";

    // 如果 KeyStore 类型是 PKCS#12, 是不支持单位为 keypair 指定独立密钥的. 此时, keyStore 的密钥就是 keypair 的密钥
    // private static final String AUTHORIZATION_SERVER_JWT_KEYPAIR_PASS = "GFLiKe0218";

    /**
     * Description: 从 KeyStore 中解析出密钥对
     *
     * @return void
     * @author LiKe
     * @date 2020-07-17 15:17:25
     */
    @SneakyThrows
    @Test
    public void extractKeyPair() {
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(KeyStoreTools.class.getClassLoader().getResourceAsStream(KEYSTORE_NAME), KEYSTORE_PASS.toCharArray());

        final PublicKey publicKey = keyStore.getCertificate(AUTHORIZATION_SERVER_JWT_KEYPAIR_ALIAS).getPublicKey();
        System.out.println("PublicKey: ");
        System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));

        final Key key = keyStore.getKey(AUTHORIZATION_SERVER_JWT_KEYPAIR_ALIAS, KEYSTORE_PASS.toCharArray());
        System.out.println("PrivateKey: ");
        System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
    }

    /**
     * Description: 从证书中读取公钥
     *
     * @return void
     * @author LiKe
     * @date 2020-07-17 16:52:09
     */
    @SneakyThrows
    @Test
    public void extractPublicKeyFromCertificateFile() {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        //生成一个证书对象并使用从输入流 inStream 中读取的数据对它进行初始化。
        Certificate certificate = certificateFactory.generateCertificate(KeyStoreTools.class.getClassLoader().getResourceAsStream("public.cert"));
        PublicKey publicKey = certificate.getPublicKey();

        System.out.println("PublicKey: ");
        System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
    }

}
